<template>
  <header>
    <div class="logo" :title="webCfg.title">
      <img src='~img/common/logo.png'/>
    </div>

    <div class="title">
      <h1>{{webCfg.title}}</h1>
      <h3 class="font-oswald">{{webCfg.titleEn}}</h3>
    </div>
    <nav>
      <!-- <div class="item" v-for="item in menuData" :class="{active:item.path===pageInfo.path.split('/')[1]}"
           :key="item.path" @click="switchMenu('/'+item.path)" @mouseenter="hoverMenu=item.path"
           v-if="(item.path==='system' && userInfo['identityId']==='5') || (item.path==='handle' && userInfo['identityId']==='4') || (item.path==='handle' && userInfo['identityId']==='5') ||(item.path!=='system'&&item.path!=='handle')"
           @mouseleave="hoverMenu=''">
        <span class="iconfont" :class="item.icon"></span>
        <span class="name mh5">{{ item.title }}</span>
        <span class="el-icon-arrow-down" v-if="item.children"></span>
        <div class="subMenu" v-if="item.children" v-show="hoverMenu===item.path">
          <div class="sub-item" v-for="itm in item.children" :key="itm.path"
               :class="{active:'/'+item.path+'/'+itm.path===activeSubMenu}" v-if="(itm.path==='disposal' && userInfo['identityId']==='2') || (itm.path==='disposal' && userInfo['identityId']==='5') || itm.path!=='disposal'"
               @click="switchMenu('/'+item.path+'/'+itm.path)">
            <span class="iconfont" :class="itm.icon"></span>
            <span class="name ml5">{{ itm.title }}</span>
          </div>
        </div>

        <div class="item-footer"></div>
      </div> -->

      <div class="item" v-for="item in menuData" :class="{active:item.path===pageInfo.path.split('/')[1]}" :key="item.path"
        @click="switchMenu('/'+item.path)" @mouseenter="hoverMenu=item.path"
        @mouseleave="hoverMenu=''">
        <span class="iconfont" :class="item.icon"></span>
        <span class="name mh5">{{ item.title }}</span>
        <span class="el-icon-arrow-down" v-if="item.children"></span>
        <div class="subMenu" v-if="item.children" v-show="hoverMenu===item.path">
          <div class="sub-item" v-for="itm in item.children" :key="itm.path"
            :class="{active:'/'+item.path+'/'+itm.path===activeSubMenu}"
            @click="switchMenu('/'+item.path+'/'+itm.path)">
            <span class="iconfont" :class="itm.icon"></span>
            <span class="name ml5">{{ itm.title }}</span>
          </div>
        </div>
        <div class="item-footer"></div>
      </div>
    </nav>

    <div class="time">
      {{ curTime }}
    </div>

    <div :class="{active:userMenuShow,user:!!1}" @mouseleave="userMenuShow=!!0">
      <span class="el-icon-user"></span>
      <span>{{ userInfo['userName'] }}</span>
      <span class="divider"></span>

      <span class="fs12">{{userInfo['identityName']}} - {{userInfo['department']}}</span>
      <!--      <span class="fs12">{{userInfo['department']}}</span>-->
      <span class="divider"></span>
      <span @click="showMsg(1)">
        <span class="el-icon-message hand" v-if="msg.length===0" title="消息列表"></span>
         <el-tooltip class="item" effect="light" content="你有新的消息！" placement="bottom" :value="true" v-else-if="msg.length!==0 && $kkui.cache.get('noteState')">
           <span class="el-icon-message mh10 hand"><i></i></span>
         </el-tooltip>
        <span class="el-icon-message mh10 hand" v-else><i></i></span>
      </span>


      <div class="el-icon-arrow-down mr10" @mouseenter="userMenuShow=1"></div>
      <ul v-show="userMenuShow" class="actionMenu">
        <li @click="editPW"><span class="el-icon-edit-outline"></span>修改密码</li>
        <li @click="logout"><span class="el-icon-bottom-left"></span>退出登录</li>
      </ul>
    </div>

    <Dialog :cfg="dialogCfg" ref="editPW">
      <el-form ref="editPwForm" :model="editPwForm" label-width="72px" :rules="editPwRules">
        <el-form-item label="原密码" class="mb20" prop="oldPw">
          <el-input v-model="editPwForm.oldPw" size="mini" clearable show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" class="mb15" prop="newPw">
          <el-input v-model="editPwForm.newPw" size="mini" clearable show-password></el-input>
        </el-form-item>
      </el-form>
    </Dialog>


    <div class="msgWin noBlueBg" v-if="showMsgFlag">
      <div class="infoBox msgStyle" v-if="msgWinMode==='msg'">
        <audio :src="soundPath" autoplay ref="audio" v-if="!mute && curMsg"></audio>
        <span class="iconfont icon-liebiao" @click="msgWinMode='list'" title="信息列表"></span>
        <span class="mute" :class="{active:mute}" @click="mute=!mute" title="静音"></span>
        <div class="img">
          <img src="~img/common/msgBg.png" alt="">
        </div>
        <h4>事件警告</h4>
        <div class="txt">
          {{curMsg && curMsg['txt']}}
        </div>
        <ul v-if="curMsg">
          <li><label>报警类型：</label>{{curMsg['type']}}</li>
          <li><label>报警路段：</label>{{curMsg['road']}}</li>
          <li><label>报警位置：</label>{{curMsg['pos']}}</li>
          <li><label>报警时间：</label>{{curMsg['time']}}</li>
        </ul>
        <div v-else style="text-align: center; line-height: 100px;">
          当前无新事件发生！
        </div>
        <div class="btns" v-if="curMsg">
          <a @click="passEvt">我已知晓</a>
          <a @click="changeNoteState">
            <div v-if="noteState">
              <span class="el-icon-video-pause mr5 fs20"></span>暂停通知
            </div>
            <div v-else>
              <span class="el-icon-video-play mr5 fs20"></span>开启通知
            </div>
          </a>
          <a @click="focusGis(curMsg['gis'])">立即处置</a>
        </div>
        <div class="btns" v-else>
          <a @click="passEvt" style="width: 100%">关闭</a>
        </div>
      </div>

      <div class="msgList msgStyle" v-else>
        <h4>信息列表</h4>
        <span class="iconfont icon-fanhui" @click="msgWinMode='msg'" title="返回"></span>
        <div class="msgs" v-if="msg.length>0">
          <div class="item" v-for="itm in msg" @click="focusGis(itm.gis)">
            {{itm.txt}}
          </div>
        </div>
        <div class="noMsg" v-else>无新的消息！</div>
      </div>
    </div>


  </header>
</template>

<script>
  import moment from 'moment';
  import Dialog from 'comp/common/Dialog';

  moment.locale('zh-cn', {
    weekdays: '日,一,二,三,四,五,六'.split(',').map(item => '星期' + item)
  });
  import {mapState} from 'vuex';

  export default {
    name: "Header",
    components: {
      Dialog
    },
    data() {
      return {
        noteState: 1,

        liveEvtIndex: null,
        liveEvtData: [],
        menuData: WebCfg.menu,
        webCfg: WebCfg,


        activeMenu: '',
        hoverMenu: '',
        activeSubMenu: '',
        curTime: null,
        newMsgFlag: false,

        userMenuShow: false,
        dialogCfg: {
          bg: 1,
          width: 400,
          height: 240,
          title: '修改密码',
          closeShow: !!1,
          footerShow: !!1,
          submit: () => {

          }
        },
        msgDialogCfg: {
          width: 380,
          height: 500,
          title: '消息列表',
          closeShow: !!1,
          footerShow: !!0,
          submit: () => {
          }
        },
        editPwForm: {
          oldPw: '',
          newPw: '',
          newPw2: ''
        },
        editPwRules: {
          oldPw: [
            {required: true, message: '请输入原密码！', trigger: 'blur'}
          ],
          newPw: [
            {required: true, message: '请输入新密码！', trigger: 'blur'}
          ],
        },

        dict: this.$kkui.cache.get('dict'),
        timer: null,
        timer2: null,
        msg: [],
        curMsg: null,
        handling: 1,
        mediaModel: 'video',

        showMsgFlag: false,
        msgWinMode: 'msg',

        mute: false,
        msgListShow: false,

        showMsgTime: 5,
        showMsgTimer: null,
        newEventNumber:-1
      }
    },
    mounted() {
      // this.getMenu();
      this.getNewMenu();
      this.timer = setInterval(() => {
        this.curTime = this.formatTime(new Date());
      }, 1000);

      if (this.$kkui.cache.get('user')['identityId'] === '2') {
        this.getLiveEvtData();
        this.timer2 = setInterval(this.getLiveEvtData, WebCfg.api.timer * 2 * 1000);

        this.startNote();
      }


    },
    computed: {
      ...mapState(["pageInfo", 'userInfo']),
      getActive() {
        return function (item) {
          let path = item.path;
          if (this.userInfo.identityId === '5') {
            path = '/system/' + path;
          }

          return path === this.pageInfo.path;
        }
      },
      soundPath() {
        return '/redalarm.mp3';
      }
    },
    methods: {
      getLiveEvtData() {
        this.$server('monitor.liveEvt', {cameraId:this.$kkui.cache.get('user').id,maxId: this.liveEvtIndex}).then(data => {
          if ( data['newList'].length > 0) {
            this.liveEvtIndex = data['newList'].reduce((p, n) => Math.max(p, n.id), 0);
          }

          this.newEventNumber=data.newEventNumber.length;

          if (data['newList'].length > 0) {
            const curTime=moment(new Date()).format('YYYY-MM-DD');


            data['newList'].forEach(item => {
              if(data['knowList'] && data['knowList'].indexOf(item.id.toString())>-1) return false;
              if(WebCfg.todayMsgFlag && new Date(item.detectedTime).getTime()<new Date(curTime).getTime()) return false;

              const camera = item['bscCamera'];
              const code = item.state <= 1 ? item['eventTypeTwoCode'] : item['type'];
              const gis = [camera['longitude'], camera['latitude']];
              let type = this.dict['event'][code];
              type = type.indexOf('-') > -1 ? type.split('-')[1] : type;
              const road = camera.road, pos = camera.name;
              let _level = '';
              const time = item.detectedTime;
              let _txt = `[${road}] 路段在 [${pos}] 位置出现`;

              if (code === '002-007-002') {
                _level = item['distance'] * 1 <= 50 ? '一' : (item['distance'] * 1 <= 100 ? '二' : '三');
                _txt += ` [雾霾]天气，能见度为${item['distance']}米,根据雾霾发展态势及其对公路安全通行影响程度，此路段建议采取${_level}级交通管制;`;
              } else {
                _txt += ` [${type}] 事件;`;
              }

              this.msg.push({
                id: item.id,
                type,
                road,
                pos,
                time,
                txt: _txt,
                gis
              });
            });
          }
          data.cancelList.forEach(item => {
            const index = this.msg.findIndex(itm => item.id === itm.id);
            if (index > -1) this.msg.splice(index, 1);
          });
        });


      },

      getNewMenu() {
        this.$server('menu.getNewMenu', {
          id: this.$kkui.cache.get('user').roleId
        }).then(data => {
          // console.log(data);
          this.menuData = data
          // this.loadList();
          // this.initEditData();
          // typeof callback === 'function' && callback();
        });
      },



      getMenu() {
        const filterMenu = (needArr, passArr) => {
          if (needArr.length === 0) needArr = WebCfg.menu.map(item => item.path);
          passArr = passArr || [];
          return WebCfg.menu.filter(item => needArr.indexOf(item.path) > -1 && passArr.indexOf(item.path) === -1)
        };

        const user = this.$kkui.cache.get('user');
        if (user.identityId === '5') {
          this.menuData = filterMenu(['system'])[0].children;
        } else if (['1', '2'].indexOf(user.identityId) > -1) {
          this.menuData = filterMenu([], ['system', 'handleCenter']);
        } else if (['3', '4'].indexOf(user.identityId) > -1) {
          this.menuData = [
            {
              title: user.identityId === '3' ? '业务指派中心' : '业务处理中心',
              path: 'handleList',
              // icon: user.identityId==='4'?'icon-weihu':'icon-jiandanchuzhi',
            }
          ]
        }


      },
      switchMenu(path) {
        if (['/fuse/kejixingan', '/patrol/project', '/patrol/data'].indexOf(path) > -1) {
          this.$kkui.alert({
            icon: 0,
            cont: '外部数据待接入中，后续将推出更新！'
          });
          return false;
        }

        if (path === '/patrol/cars' && this.$kkui.cache.get('user')['identityId'] === '1') {
          this.$kkui.alert({
            icon: 0,
            cont: '抱歉，游客没有权限查看，请登录后操作！'
          });
          return false;
        }


        if (path === this.pageInfo.path || (path.lastIndexOf('/') === 0 && ['/index', '/handle'].indexOf(path) < 0)) return false;
        this.$router.push({path: path});
        this.activeSubMenu = path;
        this.hoverMenu = '';
      },
      formatTime(time) {
        return moment(time).format('YYYY-MM-DD dddd HH:mm:ss')
      },
      editPW() {
        this.editPwForm.oldPw = '';
        this.editPwForm.newPw = '';
        this.dialogCfg.submit = () => {
          this.$refs['editPwForm'].validate((valid) => {
            if (valid) {
              this.$server('user.editPw', {
                id: this.userInfo.id,
                oldPassword: this.editPwForm.oldPw,
                newPassword: this.editPwForm.newPw
              }).then(data => {
                this.$kkui.msg({
                  code: 1,
                  cont: '密码修改成功！'
                });
                this.$refs.editPW.show = 0;
              })
            }
          });
        };
        this.$refs.editPW.show = 1;
      },
      logout() {
        this.$kkui.cache.del('user');
        this.$store.commit('renewUserInfo', null);
        this.$router.push('/login');
      },

      focusGis(gis) {
        const fn = () => {
          let map = this.$parent.$refs.section.$refs.map;
          const section = this.$parent.$refs.section.$refs.section;
          const section2 = this.$parent.$refs.section.$refs.section2;
          if (map) {
            this.$parent.$refs.section.$refs.evtCountData.activeEvtCode = '';
          }
          if (section) {
            map = section.$refs.map
          }
          if (section2) {
            map = section2.$refs.map2.$refs.map
          }
          if (map) {
            map.hiddenEvtCode = '';
            map.focusGis(gis);
          }
        };

        if (this.$route.path !== '/index') {
          this.$router.push({path: '/index'});
          this.passEvt();
          setTimeout(fn, 1000)
        } else {
          fn();
          this.passEvt();
        }


      },
      showMsg(flag) {
        if (flag) {
          if (this.msg.length > 0) {
            if (!this.showMsgFlag) { //没有弹窗
              this.curMsg = this.msg.filter(item => !item.passed)[0];
              this.showMsgFlag = true;
              this.msgWinMode = 'msg';
              this.$kkui.cache.set('noteState',true);
            }
          } else {
            this.$kkui.msg({
              icon: 0,
              cont: '当前无新的消息！'
            });
          }

        } else {
          if (this.msg.length > 0) {
            if (!this.showMsgFlag) { //没有弹窗
              if (this.showMsgTime === 5 && this.$kkui.cache.get('noteState')) {
                this.curMsg = this.msg.filter(item => !item.passed)[0];
                this.showMsgFlag = true;
                this.msgWinMode = 'msg';
              }
              this.showMsgTime++;
            }
          }

          if(this.newEventNumber===0){
            const that=this;
            that.showMsgFlag=false;
            that.msg=[];
          }
        }
      },
      passEvt() {
        this.$server('monitor.ignoreMsg',{
          knowEventId:this.curMsg.id,
          id:this.$kkui.cache.get('user').id
        }).then().catch();
        for (let i in this.msg) {
          if (this.msg[i]['id'] === this.curMsg.id) {
            this.msg[i]['passed'] = 1;
            this.msg.splice(i, 1);
            break;
          }
        }
        this.curMsg = null;
        this.showMsgTime = 0;
        this.showMsgFlag = false;

      },

      changeNoteState() {
        if (this.noteState) {
          this.showMsgTimer && clearInterval(this.showMsgTimer);
          this.showMsgTimer = null;
          this.noteState = false;
          this.$kkui.cache.set('noteState',false);
        } else {
          this.showMsgTimer = setInterval(this.showMsg, 1000);
          this.noteState = true;

          this.$kkui.cache.set('noteState',true);
        }
      },
      startNote() {
        this.showMsgTimer = setInterval(this.showMsg, 1000);
        this.noteState = true;
      },
      handleEvt() {
        this.handling = 1;
      }
    },
    beforeDestroy() {
      this.timer && clearInterval(this.timer);
      this.timer = null;
      this.timer2 && clearInterval(this.timer2);
      this.timer2 = null;
      this.showMsgTimer && clearInterval(this.showMsgTimer);
      this.showMsgTimer = null;
    }
  }
</script>

<style scoped lang="scss">
  @import "~css/header.scss";

  .msgStyle {
    border-radius: 20px;
    background: linear-gradient(180deg, rgba(252, 204, 51, 1) 5%, rgba(255, 255, 255, 1) 41%);
    box-shadow: 0 0 36px 15px rgba(252, 204, 51, 100);
    border: 1px solid rgba(187, 187, 187, 1);
    transform: translate(-50%, -50%);
    position: absolute;
    left: 50%;
    top: 50%;
    width: 380px;
    height: 500px;
    font-size: 13px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    z-index: 9999999999;
  }

  .noMsg {
    line-height: 100px;
    text-align: center;
    color: #828282;

    font-size: 13px;
  }

  .msgWin {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 999999999;
    background-color: rgba(0, 0, 0, .5);

    audio {
      display: none;
    }

    .msgStyle {
      border-radius: 20px;
      background: linear-gradient(180deg, rgba(252, 204, 51, 1) 5%, rgba(255, 255, 255, 1) 41%);
      box-shadow: 0 0 36px 15px rgba(252, 204, 51, 100);
      border: 1px solid rgba(187, 187, 187, 1);
      transform: translate(-50%, -50%);
      position: absolute;
      left: 50%;
      top: 50%;
      width: 380px;
      height: 500px;
      font-size: 13px;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;


      .iconfont, .el-icon-close {
        position: absolute;
        top: 20px;
        left: 20px;
        font-size: 22px;
        color: #fff;
        cursor: pointer;
        text-shadow: 1px 1px 1px #999;
      }
    }

    .infoBox {


      .mute {
        position: absolute;
        top: 20px;
        right: 20px;
        width: 30px;
        height: 30px;
        background: url("~img/common/mute.png") left center no-repeat;
        background-size: auto 30px;
        cursor: pointer;

        &.active {
          background-position: right center;
        }
      }

      .img {
        height: 160px;
        text-align: center;

        img {
          height: 100%;
        }
      }

      h4 {
        text-align: center;
        font-size: 18px;
        font-weight: 600;
        height: 20px;
      }

      .txt {
        text-indent: 2em;
        line-height: 20px;
        color: #808080;
        margin: 10px 20px;
      }

      li {
        padding: 0 20px;
        line-height: 20px;
        margin-bottom: 10px;
        color: #DB9F3D;

        label {
          color: #808080;
        }
      }

      .fs20 {
        font-size: 19px;
      }

      .btns {
        margin-top: auto;
        height: 50px;
        line-height: 50px;
        border-top: 1px solid #eee;
        border-radius: 0 0 20px 20px;
        overflow: hidden;
        display: flex;


        a {
          cursor: pointer;

          width: 50%;
          height: 100%;
          text-align: center;
          font-size: 14px;
          box-sizing: border-box;
          color: #aaa;
          opacity: .8;

          > div {

            display: flex;
            align-items: center;
            justify-content: center;
          }


          &:nth-child(2) {
            border-left: 1px solid #ddd;
            border-right: 1px solid #ddd;

          }

          &:last-child {
            color: #369;
          }

          &:hover {
            opacity: 1;
            background-color: #f0f0f0;
          }
        }
      }
    }

    .handling {
      h4 {
        text-align: center;
        font-size: 18px;
        font-weight: 600;
        height: 60px;
        line-height: 60px;
        position: relative;

        span {
          position: absolute;
          top: 20px;
          left: 20px;
          color: #fff;
          font-weight: bolder;
          cursor: pointer;
        }
      }

      .media {
        .switch {
          font-size: 16px;
          color: #999;
          cursor: pointer;

        }

        .win {
          width: 320px;
          height: 180px;
          border: 1px solid #ccc;
        }
      }
    }
  }

  .msgList {
    left: auto;
    right: 50px;
    transform: translate(0, -50%);

    ::-webkit-scrollbar {
      width: 6px;
      height: 8px;
      background-color: #eee;
    }

    ::-webkit-scrollbar-thumb {
      -webkit-box-shadow: inset 0 0 0 #333;
      background-color: #FDBE02;
      //background-color: var(--font-green-color);
      border-radius: 1px;
    }

    .iconfont {
      opacity: .7;
    }

    h4 {
      text-align: center;
      font-size: 18px;
      font-weight: 600;
      height: 60px;
      line-height: 60px;
    }

    .msgs {
      margin: 10px 10px 10px 20px;
      height: calc(100% - 80px);
      overflow-y: auto;
      padding-right: 5px;

      .item {
        line-height: 20px;
        margin-bottom: 10px;
        border-bottom: 1px dashed #ccc;
        cursor: pointer;
      }

    }
  }

  .msg {
    width: 340px;
    height: calc(100vh - 60px);
    background-color: #f0f0f0;
    z-index: 999999;
    position: fixed;
    right: 0;
    top: 60px;
    display: flex;
    flex-direction: column;

    > .title2 {
      display: flex;

      .left {
        color: var(--font-yellow-color);
      }

      padding: 0 10px;
      height: 36px;
      line-height: 36px;
      background-color: var(--font-blue-color);

      .right {
        color: #fff;
        margin-left: auto;
        cursor: pointer;
      }
    }

    .content {
      flex: 1;
      overflow-y: auto;
      padding: 0 10px;

      li {
        padding: 5px 0 5px 5px;
        font-size: 14px;
        line-height: 20px;
        word-break: break-all;
        margin: 5px 0;
        box-shadow: 1px 1px 1px #ccc;
        cursor: pointer;

        span {
          color: var(--font-blue-color)
        }

        &:nth-child(even) {
          background-color: rgba(51, 102, 153, .1);
        }
      }
    }
  }

  .msg2 {
    position: fixed;
    right: 0;
    top: 60px;
    padding: 8px;
    background-color: var(--font-yellow-color);
    color: #fff;
    z-index: 99999;
    border-radius: 100% 0 0 100%;
    cursor: pointer;
  }
</style>
